package cn.itcast.wushangxiantu.Fragment.guozhan;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;

import cn.itcast.wushangxiantu.BaseAdapter.FenZhengGuoJiaAdapter;
import cn.itcast.wushangxiantu.UserData.FenZhengData;
import cn.itcast.wushangxiantu.UserData.GuoJiaSYData;
import cn.itcast.wushangxiantu.UserData.User;
import cn.itcast.wushangxiantu.Activity.Login;
import cn.itcast.wushangxiantu.MessageEvent;
import cn.itcast.wushangxiantu.OkhttpUtil;
import cn.itcast.wushangxiantu.R;
import cn.itcast.wushangxiantu.ToastUtil;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link FenZhengZhanChangFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class FenZhengZhanChangFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private View view;
    private Context context;
    private int gj_id;
    private ViewHolder viewHolder;
    private FenZhengGuoJiaAdapter adapter;
    private FenZhengData fenZhengData;
    private int num=0;
    public FenZhengZhanChangFragment(Context context, int gj_id) {
        this.context = context;
        this.gj_id = gj_id;
    }

    public FenZhengZhanChangFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment FenZhengZhanChangFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static FenZhengZhanChangFragment newInstance(String param1, String param2) {
        FenZhengZhanChangFragment fragment = new FenZhengZhanChangFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_fen_zheng_zhan_chang, container, false);
        viewHolder = new ViewHolder(view);
        return view;
    }

    class ViewHolder implements View.OnClickListener {
        public View rootView;
        public TextView tvDiQu;
        public TextView tvNMNumber;
        public TextView tvTime;
        public Button btnGetSY;
        public Spinner spDQ;
        public Button btnSetDQ;
        public Button btnGetAll;
        public TextView tvNumber;
        public ListView lv;

        public ViewHolder(View rootView) {
            this.rootView = rootView;
            this.tvDiQu = (TextView) rootView.findViewById(R.id.tvDiQu);
            this.tvNMNumber = (TextView) rootView.findViewById(R.id.tvNMNumber);
            this.tvTime = (TextView) rootView.findViewById(R.id.tvTime);
            this.btnGetSY = (Button) rootView.findViewById(R.id.btnGetSY);
            this.spDQ = (Spinner) rootView.findViewById(R.id.spDQ);
            this.btnSetDQ = (Button) rootView.findViewById(R.id.btnSetDQ);
            this.btnGetAll = (Button) rootView.findViewById(R.id.btnGetAll);
            this.tvNumber = (TextView) rootView.findViewById(R.id.tvNumber);
            this.lv = (ListView) rootView.findViewById(R.id.lv);
            btnGetSY.setOnClickListener(this);
            btnSetDQ.setOnClickListener(this);
            btnGetAll.setOnClickListener(this);
            getSYData(Login.getUser().getUsernumber(), Login.getUser().getPassword());
            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    num=i;
                    String content=fenZhengData.getGuoJiaZhanChang().get(i).getName()+"\n国家等级："+fenZhengData.getGuoJiaZhanChang().get(i).getDj()+"\n地区收益："+fenZhengData.getGuoJiaZhanChang().get(i).getGjsy();
                    switch ((int) spDQ.getSelectedItemId()){
                        case 0:
                            content+="\n富裕地区攻打消耗1次掠夺机会";
                            break;
                        case 1:
                            content+="\n普通地区攻打消耗2次掠夺机会";
                            break;
                        case 2:
                            content+="\n贫乏地区攻打消耗3次掠夺机会";
                            break;
                    }
                    GeneralDialog("仙盟详情",content,0);
                }
            });
        }

        private void getSYData(String usernumber, String password) {
            OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "&need=findGuoJiaShouYi" + "&passWord=" + password + "&userNumber=" + usernumber, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    try {
                        Log.v("findGuoJiaShouYi", e.getMessage());
                    } catch (Exception e1) {

                    }
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String res = response.body().string();
                    Log.v("findGuoJiaShouYi", res);
                    Message message = new Message();
                    GuoJiaSYData user = new Gson().fromJson(res, GuoJiaSYData.class);
                    message.what = 1;
                    message.obj = user;
                    handler.sendMessage(message);
                }
            });
        }

        Handler handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(@NonNull Message message) {
                switch (message.what) {
                    case 1:
                        GuoJiaSYData data = (GuoJiaSYData) message.obj;
                        if (null != data) {
                            tvTime.setText("上次收益：" + data.getTime());
                            tvNumber.setText("今日剩余掠夺次数：" + data.getSynumber());
                            tvNMNumber.setText(data.getNmdj() + "级历练弟子" + data.getNmnumber() + "个");
                            switch (data.getDt()) {
                                case 3:
                                    tvDiQu.setText("富裕地区");
                                    break;
                                case 2:
                                    tvDiQu.setText("普通地区");
                                    break;
                                case 1:
                                    tvDiQu.setText("贫乏地区");
                                    break;
                                case 0:
                                    tvDiQu.setText("无");
                                    break;
                            }
                        } else {
                            ToastUtil.toast(context);
                        }
                        break;
                    case 2:
                        User user= (User) message.obj;
                        if (null!=user){
                            GeneralDialog("战场详情",user.getStw(),-1);
                            getSYData(Login.getUser().getUsernumber(), Login.getUser().getPassword());
                            EventBus.getDefault().post(new MessageEvent("getGuoJiaXinxi"));
                        }else {
                            ToastUtil.toast(context);
                        }
                        break;
                    case 3:
                         fenZhengData= (FenZhengData) message.obj;
                        if (null!=fenZhengData){
                            if (adapter==null){
                                adapter=new FenZhengGuoJiaAdapter(context);
                            }
                            adapter.setData(fenZhengData);
                            lv.setAdapter(adapter);
                        }else {
                            ToastUtil.toast(context);
                        }
                        break;
                }
                return false;
            }
        });

        public void GeneralDialog(String head, String content, final int num) {
            /**
             * 普通对话框
             * 1标题
             * 2内容
             */
            AlertDialog dialog;
            AlertDialog.Builder builder = new AlertDialog.Builder(context)
                    .setTitle(head)

                    .setMessage(content)
                    .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            switch (num) {
                                case 0:
                                    //攻打国家
                                    kaizhan(Login.getUser().getUsernumber(),Login.getUser().getPassword(),fenZhengData.getGuoJiaZhanChang().get(num).getName());
                                    break;
                                case 1:
                                    //修改收益地区
                                    setShouYi(Login.getUser().getUsernumber(), Login.getUser().getPassword(), 3 - spDQ.getSelectedItemId());
                                    break;
                            }
                        }
                    });
            dialog = builder.create();
            dialog.show();
        }

        private void kaizhan(String usernumber, String password, String name) {
            OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "&need=kaizhan" + "&passWord=" + password + "&userNumber=" + usernumber + "&gj_name=" + fenZhengData.getGuoJiaZhanChang().get(num).getName(), new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    try {
                        Log.v("kaizhan", e.getMessage());
                    } catch (Exception e1) {

                    }
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String res = response.body().string();
                    Log.v("kaizhan", res);
                    Message message = new Message();
                    User user = new Gson().fromJson(res, User.class);
                    message.what = 2;
                    message.obj = user;
                    handler.sendMessage(message);
                }
            });
        }

        private void setShouYi(String usernumber, String password, long l) {
            OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "&need=setShouYi" + "&passWord=" + password + "&userNumber=" + usernumber + "&num=" + l, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    try {
                        Log.v("setShouYi", e.getMessage());
                    } catch (Exception e1) {

                    }
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String res = response.body().string();
                    Log.v("setShouYi", res);
                    Message message = new Message();
                    User user = new Gson().fromJson(res, User.class);
                    message.what = 2;
                    message.obj = user;
                    handler.sendMessage(message);
                }
            });
        }

        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.btnGetSY:
                    getShouYi(Login.getUser().getUsernumber(),Login.getUser().getPassword());
                    break;
                case R.id.btnSetDQ:
                    GeneralDialog("战场详情","确定要修改收益地区吗，这样导致你之前的收益时间重置",1);
                    break;
                case R.id.btnGetAll:
                    findZhanChangByNum(Login.getUser().getUsernumber(),Login.getUser().getPassword(),3-spDQ.getSelectedItemId());
                    break;
            }
        }

        private void findZhanChangByNum(String usernumber, String password, long l) {
            OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "&need=findZhanChangByNum" + "&passWord=" + password + "&userNumber=" + usernumber +"&num="+l, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    try {
                        Log.v("findZhanChangByNum", e.getMessage());
                    } catch (Exception e1) {

                    }
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String res = response.body().string();
                    Log.v("findZhanChangByNum", res);
                    Message message = new Message();
                    FenZhengData data = new Gson().fromJson(res, FenZhengData.class);
                    message.what = 3;
                    message.obj = data;
                    handler.sendMessage(message);
                }
            });
        }

        private void getShouYi(String usernumber, String password) {
            OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "&need=getShouYi" + "&passWord=" + password + "&userNumber=" + usernumber , new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    try {
                        Log.v("getShouYi", e.getMessage());
                    } catch (Exception e1) {

                    }
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String res = response.body().string();
                    Log.v("getShouYi", res);
                    Message message = new Message();
                    User user = new Gson().fromJson(res, User.class);
                    message.what = 2;
                    message.obj = user;
                    handler.sendMessage(message);
                }
            });
        }
    }
}